
// Copyright (c) 2002 HTHK
package com.ffpc.util;

import java.io.*;
import java.net.*;

public class SocketMail
{
  private String host;
  private int port;
  private StringBuffer body;
  private String subject;
  private PrintWriter out;
  private BufferedReader in;
  private Socket s;

	public SocketMail()
  {
	 //try
	 //{
		//this.host = new String(InetAddress.getLocalHost().getHostName());
		this.host = new String("ebisdevp");
		this.port = 25;
		subject = new String();
		body = new StringBuffer();
	 //}
	 //catch (IOException e)
	 //{
	 //  e.printStackTrace();
	 //}
  }

  public SocketMail(String host, int port)
  {
	  this.host = new String(host);
	  this.port = port;
	  subject = new String();
	  body = new StringBuffer();
  }

  public void setSubject(String subject)
  {
	 this.subject = subject;
  }

  public String getSubject()
  {
	 if (this.subject==null)
		this.subject = new String("socket mail");
	 return this.subject;
  }

  public void writeln(String str)
  {
	 if (str==null)
		str="";
	 this.body = new StringBuffer(str + "\n");
  }

  public void write(String str)
  {
	 if (str==null)
		str="";
	 this.body = new StringBuffer(str);
  }

  public void appendln(String str)
  {
	 if (str==null)
		str="";
	 this.body.append(str + "\n");
  }

  public void append(String str)
  {
	 if (str==null)
		str="";
	 this.body.append(str);
  }

  public StringBuffer getBody()
  {
	 return body;
  }

  public void send(String from, String[] to)
  {
	 for (int i=0; to!=null && i<to.length; i++)
	 {
		if (to[i]!=null && to[i].indexOf("@")!=-1)
		  send(from,to[i]);
	 }
  }

  public void send(String from, String to)
  {
	 try
		{
		s = new Socket(host, port);
		  out = new PrintWriter(s.getOutputStream());
		  in = new BufferedReader(new InputStreamReader(s.getInputStream()));
			send(null);
		send("HELO " + host);
		send("MAIL FROM: " + from);
		send("RCPT TO: " + to);
		send("DATA");
		out.println("Subject: " + getSubject() + "\n");
		out.println(getBody().toString());
		send(".");
		close();
		}
	 catch (UnknownHostException e)
	 {
		System.out.println("UnknownHostException: " + e.getMessage());
	 }
		catch (IOException e)
		{
			System.out.println("ERROR::"+e.toString());
		e.printStackTrace();
		}
	 catch (Exception e)
	 {
		System.out.println("ERROR::"+e.toString());
		e.printStackTrace();
	 }
  }

  private void send(String s)
	 throws IOException
  {
	 if (s != null)
	 {
		//System.out.println(s + "\n");
		out.println(s);
		out.flush();
	 }
	 String line = in.readLine();
  }

  private void close()
  {
	 try
		{
		if (in!=null)
		  in.close();
		if (out!=null)
		  out.close();
		if (s!=null)
		  s.close();
	 }
	 catch (Exception e)
	 {
		System.out.println("ERROR::"+e.toString());
		e.printStackTrace();
	 }
  }
}

 
